package org.graduation.project.controller;

import org.graduation.common.NoPermissionException;
import org.graduation.feignapi.RBACClient;
import org.graduation.model.common.RBAC.Permissions;
import org.graduation.model.common.ResponseResult;
import org.graduation.model.common.project.Task;
import org.graduation.model.dtos.RBAC.CheckPermissionsDTO;
import org.graduation.project.service.TaskAndUserService;
import org.graduation.project.service.TaskService;
import org.graduation.utils.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/project/phase/task/user")
public class TaskAndUserController {
    @Autowired
    private TaskAndUserService taskAndUserService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private Token token;
    @Autowired
    private RBACClient rbacClient;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ResponseResult list(@RequestParam Long taskId, HttpServletRequest request) {
        Permissions permission = Permissions.VIEW_TASK;
        int uid = token.getUidByToken(token.getTokenByRequest(request));
        Task task = taskService.getById(taskId);
        if (!checkPermission(task.getPId(), uid, permission)) {
            throw new NoPermissionException(permission);
        }
        return ResponseResult.success(taskAndUserService.getUsersByTaskId(taskId));
    }

    private boolean checkPermission(Long pId, Integer uid, Permissions permission) {
        return rbacClient.check(new CheckPermissionsDTO(pId, uid, permission)).getCode() == 200;
    }
}
